"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { FileSpreadsheet, Upload, Download, CheckCircle, AlertCircle, Database, Loader2 } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { 
  Dialog, 
  DialogContent, 
  DialogDescription, 
  DialogHeader, 
  DialogTitle, 
  DialogTrigger 
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"

interface ImportResult {
  success: boolean;
  count?: number;
  message?: string;
  errors?: string[];
}

export default function DataImportPage() {
  const { toast } = useToast()
  const [importing, setImporting] = useState(false)
  const [importProgress, setImportProgress] = useState(0)
  const [importResults, setImportResults] = useState<ImportResult[]>([])
  const [showCustomImportDialog, setShowCustomImportDialog] = useState(false)
  const [customDataType, setCustomDataType] = useState("")
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  
  // SQLite 相关状态
  const [sqliteStats, setSqliteStats] = useState<any>(null)
  const [loadingStats, setLoadingStats] = useState(false)

  useEffect(() => {
    loadSqliteStats()
  }, [])

  const loadSqliteStats = async () => {
    try {
      setLoadingStats(true)
      const response = await fetch('/api/sqlite-dashboard-stats')
      if (response.ok) {
        const data = await response.json()
        setSqliteStats(data)
      }
    } catch (error) {
      console.error('获取SQLite统计失败:', error)
    } finally {
      setLoadingStats(false)
    }
  }

  const handleJsonToSqliteMigration = async () => {
    try {
      setImporting(true)
      setImportProgress(0)
      
      toast({
        title: "开始迁移",
        description: "正在将JSON数据迁移到SQLite数据库...",
      })

      const response = await fetch('/api/migrate-to-sqlite', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      const result = await response.json()

      if (response.ok) {
        setImportProgress(100)
        setImportResults([{
          success: true,
          count: result.deviceCount,
          message: `成功迁移 ${result.deviceCount} 个设备到SQLite数据库`
        }])
        
        toast({
          title: "迁移完成",
          description: `成功迁移 ${result.deviceCount} 个设备`,
        })

        // 刷新统计信息
        await loadSqliteStats()
      } else {
        throw new Error(result.error || '迁移失败')
      }
    } catch (error) {
      console.error('迁移失败:', error)
      setImportResults([{
        success: false,
        message: error instanceof Error ? error.message : '迁移失败'
      }])
      
      toast({
        title: "迁移失败",
        description: error instanceof Error ? error.message : '迁移失败',
        variant: "destructive",
      })
    } finally {
      setImporting(false)
    }
  }

  const handleExcelToSqliteImport = async () => {
    try {
      setImporting(true)
      setImportProgress(0)
      
      const importSteps = [
        { name: "属性表", file: "06-18/0618-属性表.xlsx" },
        { name: "设备表", file: "06-18/0618-设备表.xlsx" },
        { name: "计量单位定义表", file: "06-18/计量单位定义表.csv" }
      ]

      toast({
        title: "开始导入",
        description: "正在从Excel文件导入数据到SQLite数据库...",
      })

      const results: ImportResult[] = []
      
      for (let i = 0; i < importSteps.length; i++) {
        const step = importSteps[i]
        setImportProgress((i / importSteps.length) * 80)
        
        try {
          const response = await fetch('/api/import-excel-to-sqlite', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              filename: step.file,
              dataType: step.name
            })
          })

          const result = await response.json()
          
          if (response.ok) {
            results.push({
              success: true,
              count: result.count,
              message: `${step.name}: 成功导入 ${result.count} 条记录`
            })
          } else {
            results.push({
              success: false,
              message: `${step.name}: ${result.error}`
            })
          }
        } catch (error) {
          results.push({
            success: false,
            message: `${step.name}: 导入失败`
          })
        }
      }

      setImportProgress(100)
      setImportResults(results)
      
      const successCount = results.filter(r => r.success).length
      if (successCount === importSteps.length) {
        toast({
          title: "导入完成",
          description: "所有数据已成功导入SQLite数据库",
        })
      } else {
        toast({
          title: "导入部分完成",
          description: `${successCount}/${importSteps.length} 个数据源导入成功`,
          variant: "destructive",
        })
      }

      // 刷新统计信息
      await loadSqliteStats()
    } catch (error) {
      toast({
        title: "导入失败",
        description: "Excel数据导入过程中发生错误",
        variant: "destructive",
      })
    } finally {
      setImporting(false)
    }
  }

  const handleCustomImport = async () => {
    if (!selectedFile || !customDataType) {
      toast({
        title: "参数错误",
        description: "请选择文件并指定数据类型",
        variant: "destructive",
      })
      return
    }

    try {
      setImporting(true)
      setShowCustomImportDialog(false)

      const formData = new FormData()
      formData.append('file', selectedFile)
      formData.append('dataType', customDataType)

      const response = await fetch('/api/import-custom-to-sqlite', {
        method: 'POST',
        body: formData
      })

      const result = await response.json()

      if (response.ok) {
        setImportResults([{
          success: true,
          count: result.count,
          message: `${customDataType}: 成功导入 ${result.count} 条记录`
        }])
        
        toast({
          title: "导入成功",
          description: `已导入 ${result.count} 条记录`,
        })

        await loadSqliteStats()
      } else {
        throw new Error(result.error)
      }
    } catch (error) {
      setImportResults([{
        success: false,
        message: error instanceof Error ? error.message : '导入失败'
      }])
      
      toast({
        title: "导入失败",
        description: error instanceof Error ? error.message : '导入失败',
        variant: "destructive",
      })
    } finally {
      setImporting(false)
      setSelectedFile(null)
      setCustomDataType("")
    }
  }

  const clearSqliteDatabase = async () => {
    if (!confirm('确定要清空SQLite数据库吗？此操作不可撤销。')) {
      return
    }

    try {
      const response = await fetch('/api/clear-sqlite', {
        method: 'POST'
      })
      
      if (response.ok) {
        toast({
          title: "数据库已清空",
          description: "SQLite数据库已成功清空",
        })
        setSqliteStats(null)
        setImportResults([])
      } else {
        throw new Error('清空数据库失败')
      }
    } catch (error) {
      toast({
        title: "清空失败",
        description: error instanceof Error ? error.message : '清空数据库失败',
        variant: "destructive",
      })
    }
  }

  return (
    <div className="container mx-auto py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold tracking-tight mb-2">数据导入管理</h1>
          <p className="text-muted-foreground">
          将Excel文件或JSON数据导入到SQLite数据库中，统一管理实体对象信息
          </p>
      </div>

      {/* SQLite数据库状态 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Database className="h-5 w-5" />
            SQLite数据库状态
          </CardTitle>
          <CardDescription>当前数据库中的数据概览</CardDescription>
        </CardHeader>
        <CardContent>
          {loadingStats ? (
            <div className="flex items-center gap-2">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span>加载统计信息...</span>
            </div>
          ) : sqliteStats ? (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{sqliteStats.totalDevices}</div>
                <div className="text-sm text-gray-600">总设备数</div>
              </div>
              {sqliteStats.specialtyStats?.slice(0, 3).map((stat: any, index: number) => (
                <div key={index} className="text-center p-4 bg-gray-50 rounded-lg">
                  <div className="text-xl font-bold">{stat.count}</div>
                  <div className="text-sm text-gray-600">{stat.name}</div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              数据库为空，请导入数据
            </div>
          )}
        </CardContent>
      </Card>

      {/* 导入选项 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
        {/* JSON到SQLite迁移 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Database className="h-5 w-5" />
              JSON数据迁移
            </CardTitle>
            <CardDescription>
              将现有的JSON数据迁移到SQLite数据库
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Button
              onClick={handleJsonToSqliteMigration}
              disabled={importing}
              className="w-full"
            >
              {importing ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  迁移中...
                </>
              ) : (
                <>
                  <Upload className="h-4 w-4 mr-2" />
                  开始迁移
                </>
              )}
            </Button>
          </CardContent>
        </Card>

        {/* Excel到SQLite导入 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileSpreadsheet className="h-5 w-5" />
              Excel数据导入
            </CardTitle>
            <CardDescription>
              从Excel文件导入设备和参数数据到SQLite
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Button
              onClick={handleExcelToSqliteImport}
              disabled={importing}
              className="w-full"
            >
              {importing ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  导入中...
                </>
              ) : (
                <>
                  <Upload className="h-4 w-4 mr-2" />
                  导入Excel
                </>
              )}
            </Button>
          </CardContent>
        </Card>

        {/* 自定义数据导入 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Upload className="h-5 w-5" />
              自定义导入
            </CardTitle>
            <CardDescription>
              导入其他格式的数据文件
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Dialog open={showCustomImportDialog} onOpenChange={setShowCustomImportDialog}>
              <DialogTrigger asChild>
                <Button variant="outline" className="w-full">
                  选择文件
            </Button>
              </DialogTrigger>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
                  <DialogTitle>导入自定义数据</DialogTitle>
            <DialogDescription>
                    选择文件并指定数据类型，系统将自动识别并导入到SQLite数据库
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="dataType">数据类型</Label>
              <Input
                id="dataType"
                placeholder="如：设备清单、工程图纸、技术规范等"
                value={customDataType}
                onChange={(e) => setCustomDataType(e.target.value)}
              />
            </div>
            <div className="space-y-2">
                    <Label htmlFor="file">选择文件</Label>
              <Input
                id="file"
                type="file"
                      accept=".xlsx,.xls,.csv"
                onChange={(e) => {
                  const file = e.target.files?.[0]
                  setSelectedFile(file || null)
                }}
              />
              {selectedFile && (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                        <FileSpreadsheet className="h-4 w-4" />
                  <span>{selectedFile.name}</span>
                  <span>({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)</span>
                </div>
              )}
            </div>
          </div>
                <div className="flex justify-end gap-3">
                  <Button variant="outline" onClick={() => setShowCustomImportDialog(false)}>
              取消
            </Button>
                  <Button onClick={handleCustomImport} disabled={!selectedFile || !customDataType}>
                    <Upload className="h-4 w-4 mr-2" />
                    开始导入
            </Button>
                </div>
        </DialogContent>
      </Dialog>
          </CardContent>
        </Card>
      </div>

      {/* 导入进度 */}
      {importing && (
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>导入进度</CardTitle>
          </CardHeader>
          <CardContent>
            <Progress value={importProgress} className="w-full" />
            <p className="text-sm text-muted-foreground mt-2">
              正在处理数据... {importProgress}%
            </p>
          </CardContent>
        </Card>
      )}

      {/* 导入结果 */}
      {importResults.length > 0 && (
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>导入结果</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {importResults.map((result, index) => (
                <div
                  key={index}
                  className={`flex items-center gap-3 p-3 rounded-lg ${
                    result.success ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'
                  }`}
                >
                  {result.success ? (
                    <CheckCircle className="h-5 w-5 text-green-600" />
                  ) : (
                    <AlertCircle className="h-5 w-5 text-red-600" />
                  )}
                  <div>
                    <p className={result.success ? 'text-green-800' : 'text-red-800'}>
                      {result.message}
                    </p>
                    {result.errors && result.errors.length > 0 && (
                      <ul className="text-sm text-red-600 mt-1">
                        {result.errors.map((error, errorIndex) => (
                          <li key={errorIndex}>• {error}</li>
                        ))}
                      </ul>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 数据库管理 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-red-600">危险操作</CardTitle>
          <CardDescription>
            以下操作将永久删除数据，请谨慎操作
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Button 
            variant="destructive" 
            onClick={clearSqliteDatabase}
            disabled={importing}
          >
            <AlertCircle className="h-4 w-4 mr-2" />
            清空SQLite数据库
          </Button>
        </CardContent>
      </Card>
    </div>
  )
} 